const fp = require('lodash/fp');

class Container {
    static of(value) {
        return new Container(value);
    }
    
    constructor(value) {
        this._value = value;
    }
    
    map(fn) {
        return Container.of(fn(this._value));
    }
}

class Maybe {
    static of(x) {
        return new Maybe(x);
    }
    
    constructor(value) {
        this._value = value;
    }

    isNothing() {
        return this._value === null || this._value === undefined;
    }
    
    map(fn) {
        return this.isNothing() ? this :  Maybe.of(fn(this._value));
    }
}

/*-------------------------------------------------------------------------------------------------------- */

//  题目1

let maybe = Maybe.of([5, 6, 1])

const exl = y => maybe.map(array => fp.map(x => fp.add(x, y), array))

console.log(exl(1))

// Maybe { _value: [ 6, 7, 2 ] }

/*-------------------------------------------------------------------------------------------------------- */

//  题目2
const xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do']);
const ex2 = () => xs.map(fp.first);

console.log(ex2())

// Container { _value: 'do' }

/*-------------------------------------------------------------------------------------------------------- */

//  题目3

const safeProp = fp.curry((x, o) => Maybe.of(o(x)));
const user = { id: 2, name: 'Albert' }

const ex3 = () => {
    const curried = safeProp(user);
    return curried(value => fp.first(value.name))
}

console.log(ex3())

// Maybe { _value: 'A' }
/*-------------------------------------------------------------------------------------------------------- */

//  题目4

const ex4 = n => {
    const maybe = Maybe.of(n);
    return maybe.map(parseInt)._value;
}

console.log(ex4('4'))

// 4
/*-------------------------------------------------------------------------------------------------------- */